package JVM.privateDefineClassLoader;


import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

/**
 * @className: MyClassLoader
 * @Description:
 * @Author: wangyifei
 * @Date: 2022/8/7 11:06
 */
public class MyClassLoader extends ClassLoader{

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        System.out.println("self-define classLoader");
        File file = new File("D:\\Download\\JVM\\privateDefineClassLoader/MyClass.class");
        try{
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bis = new ByteArrayOutputStream();
            int b = 0 ;
            while( (b = fis.read()) !=0){
                bis.write(b);
            }
            byte[] bytes = bis.toByteArray();
            bis.close();
            fis.close();
            return defineClass(name , bytes , 0 , bytes.length);
        }catch (Exception e){
           e.printStackTrace();
        }
        return super.findClass(name);
    }

    public static void main(String[] args) {
        MyClassLoader myClassLoader = new MyClassLoader();
        try {
            Class<?> aClass = myClassLoader.loadClass("JVM.privateDefineClassLoader.MyClass");
            Object o = aClass.newInstance();
            System.out.println(o);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
